package com.gitee.dolt.core.base;


import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.gitee.dolt.core.exception.code.ExceptionCode;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Map;


/**
 * @author LYH
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class Result<T> {

    private int code;
    private String message;
    private T data;

    /**
     * 是否执行默认
     */
    @JsonIgnore
    private boolean execDefault;

    private Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public Result setOk() {
        this.setCode(ExceptionCode.OK.getCode());
        return this;
    }

    public static Result execDefault(boolean execDefault) {
        return ok().setExecDefault(execDefault);
    }

    public static <E> Result<E> result(int code, String message, E data) {
        return new Result<E>(code, message, data);
    }

    public static <E> Result<E> result(int code, String message) {
        return result(code, message, null);
    }

    public static <E> Result<E> result(ExceptionCode exceptionCode) {
        return result(exceptionCode.getCode(), exceptionCode.getMsg());
    }

    public static <E> Result<E> ok(E e) {
        return result(ExceptionCode.OK.getCode(), ExceptionCode.OK.getMsg(), e);
    }

    public static <E> Result<E> ok() {
        return ok(null);
    }

    public Map<String, Object> toMap() {
        Map<String, Object> map = BeanUtil.beanToMap(this);
        map.remove("execDefault");
        return map;
    }
}
